﻿using Fast;
using Fast.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using System;
using System.Linq;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// 
    /// </summary>
    [SkipScan]
    public static class DynamicApiControllerServiceCollectionExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configure"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public static IServiceCollection AddDynamicApiController(this IServiceCollection services, Action<DynamicApiControllerOptions> configure = null)
        {
            var partManager = services.FirstOrDefault(d => d.ServiceType == typeof(ApplicationPartManager))?.ImplementationInstance as ApplicationPartManager;

            if (partManager == null)
            {
                throw new InvalidOperationException("\"AddDynamicWebApi\" 必须在 \"AddMvc\" 之后。");
            }

            services.AddConfigureOptions<DynamicApiControllerOptions>(configure);

            // 添加自定义控制器检查器
            partManager.FeatureProviders.Add(new DynamicApiControllerFeatureProvider());

            services.Configure<MvcOptions>(o =>
            {
                // 注册控制器路由信息转换器
                o.Conventions.Add(new DynamicApiControllerConvention());
            });

            return services;
        }
    }
}
